<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/player.php';
require_once APP_ROOT . 'model/common/categories.php';
require_once APP_ROOT . 'model/common/session.php';
require_once APP_ROOT . 'model/common/form.php';
require_once APP_ROOT . 'model/common/state.php';
require_once APP_ROOT . 'model/common/date.php';


// article create/update form
class PlayerFormController extends FormController {

	var $admin_user = false;
	var $staff_user = false;
	var $view; // current view

	function setUserType($admin_user=false, $staff_user = false) {
		$this->admin_user = $admin_user;
        $this->staff_user = $staff_user;
	}

    function setView(&$view) {
    	$this->view = $view;
    }


	 function PlayerFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete

        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean
        $this->addChild('players', new ButtonController(new Delegate($this, 'back'))); // back

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('name')));
		$this->addRule(new PatternRule('contact_phone','/^[0-9- +]{11,}$/'));
		$this->addRule(new PatternRule('coach_phone','/^[0-9- +]{11,}$/'));
		//$this->addRule(new PatternRule('weight','/^[0-9]{1,}[\.,]{0,1}[0-9]{0,2}$/'));
		//$this->addRule(new PatternRule('height','/^[0-9]{3,}$/'));
        $this->addRule(new PatternRule('height','/^[0-9]{1,2}[\']{1}[0-9]{0,1}$/'));
		$this->addRule(new PatternRule('weight','/^[0-9]{3,}$/'));
		$this->addRule(new PatternRule('gpa','/^[0-9]{1,}[\.,]{0,1}[0-9]{0,2}$/'));
		$this->addRule(new PatternRule('sat','/^[0-9]{1,}[\.,]{0,1}[0-9]{0,4}$/'));

		$zipRule=& new PatternRule('school_zip','/^[0-9]{4,5}$/');
		$zipRule->setGroup('ziprule');
		$this->addRule($zipRule);

        $this->registerOnLoadListener(new Delegate($this, 'load'));
        //$this->registerOnActivateListener(new Delegate($this, 'check'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }


     function checkCategories(&$source, &$request, &$responseModel) {
        // check that two categories are linked
            $category_id = $responseModel->get('category_id');
            $category2_id = $responseModel->get('category2_id');

            //print $category_id.'/'.$category2_id ;

            if (!$category_id && !$category2_id) {
                $responseModel->set('msg',"Error: At least one category must be selected!");
            	return false;
            }
            if ($category_id && $category2_id) {
            	$linked = CategoriesModel::AreCategoriesLinked($category_id, $category2_id);
            	//print 'result of check '.$linked;
            	if (!$linked) {
                    $responseModel->set('msg',"Error: The categories selected are not linked!");
                    //print $category_id.'/'.$category2_id." Not Linked!";
            		return false;
            	}
            }
            return true;
     }

     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';

            if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';


            //prepare author user
            $author_user_id = 0;
            if (Session::isLogin()) {
            	$author_user_id = Session::getUserId();
            }
            if ($author_user_id) $responseModel->set('user_id',$author_user_id);
            $tz =& new MyTimeZone();
            $responseModel->set('date_added', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );


            $player_id = Player::insertPlayer($responseModel);
            if ($player_id) {
            	$responseModel->set('player_id', $player_id);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);


                return 'createOK';
            } else {
                return 'failure';
            }
        } else {
            //$responseModel->set('ShowPreview', TRUE);
        }
     }


	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }


     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$player_id = $request->getParameter('player_id');

        	if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';

            //prepare author user
            $admin_user_id = 0;
            if (Session::isLogin()) {
            	$admin_user_id = Session::getUserId();
            }
            if ($admin_user_id) $responseModel->set('admin_user_id',$admin_user_id);

            if ($player_id) Player::updatePlayer($player_id, $responseModel);
            return 'saveOK';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'cleanOK';
    }

    function back(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'index';
    }

     function load(&$source, &$request, &$responseModel) {
     	$player_id = $request->getParameter('player_id');
     	if ($player_id) {
        	$record =& Player::getRecord($player_id);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            $sat = $responseModel->get('sat');
        	$responseModel->set('sat', number_format($sat,0));

        	$gpa = $responseModel->get('gpa');
        	$responseModel->set('gpa', number_format($gpa,0));

            //load width and height of the image
            $photo_url = $responseModel->get('photo_url');
	    $photo_url = str_replace(' ','%20',$photo_url); //REPLACE THE SPACES
            list($width, $height, $type, $attr) = @getimagesize(HOST.$photo_url);
            $responseModel->set('photo_width', $width);
            $responseModel->set('photo_height', $height);

        	//$photo_url = $responseModel->get('photo_url');
        	//print 'Photo: '.$photo_url;

            return 'success';

        }
     }

     //prepare the form view
     function prepare(&$source, &$request, &$responseModel, &$template) {
     	//print 'Prepare form...';
     	if ($this->admin_user) {
     		$responseModel->set('admin_user',1);
     	}
     	if ($this->staff_user) $responseModel->set('staff_user',1);

        //print $responseModel->get('photo_url');

        //populate categories
        $categories1 =& CategoriesModel::getSportCategories(false,false);
        //print_r($categories1);
        $categories2 =& CategoriesModel::getCommunityCategories(false,false);
        $category1 =& $template->getChild('category_id');
        $category2 =& $template->getChild('category2_id');
        $category1->setChoices($categories1);
        $category2->setChoices($categories2);

        //populate classes
        $classes =& Player::getClassesList();
        $class_element =& $template->getChild('class');
        $class_element->setChoices($classes);

        //populate gender
        $genders =& Player::getGendersList();
        $gender_element =& $template->getChild('gender');
        $gender_element->setChoices($genders);

        // populate states
        $state = $responseModel->get('school_state');
        $states =& $template->getChild('school_state');
        $states_list =& State::getStates();
        $states->setChoices($states_list);

        // populate teams
        $team = $responseModel->get('team');
        $teams =& $template->getChild('team');
        $teams_list =& Player::getTeamsList();
        $teams->setChoices($teams_list);

        // populate projected college levels
        $level =& $template->getChild('projected_level');
        $levels_list =& Player::getCollegeLevels();
        $level->setChoices($levels_list);


     }
}

?>